from PyQt5.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QTableWidget, QTableWidgetItem, QHeaderView, QComboBox, QMessageBox


class ParamEditor(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initUI()

    def initUI(self):
        self.layout = QVBoxLayout()

        # 表格显示 Params
        self.table = QTableWidget()
        self.table.setRowCount(0)
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(["Name", "Type", "Value", "Description", "Unit"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.setEditTriggers(QTableWidget.AllEditTriggers)
        self.layout.addWidget(self.table)

        # 添加和删除按钮
        button_layout = QHBoxLayout()
        self.add_button = QPushButton("Add Param")
        self.add_button.clicked.connect(self.add_param)
        self.delete_button = QPushButton("Delete Param")
        self.delete_button.clicked.connect(self.delete_param)
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.delete_button)
        self.layout.addLayout(button_layout)

        self.setLayout(self.layout)

    def add_param(self):
        row_count = self.table.rowCount()
        self.table.insertRow(row_count)
        self.table.setItem(row_count, 0, QTableWidgetItem(""))  # Name
        self.table.setCellWidget(row_count, 1, QComboBox())  # Type
        self.table.cellWidget(row_count, 1).addItems(["double", "int", "bool", "string"])
        self.table.setItem(row_count, 2, QTableWidgetItem(""))  # Value
        self.table.setItem(row_count, 3, QTableWidgetItem(""))  # Description
        self.table.setItem(row_count, 4, QTableWidgetItem(""))  # Unit

    def delete_param(self):
        selected_rows = self.table.selectionModel().selectedRows()
        if selected_rows:
            for row in sorted(selected_rows, reverse=True):
                self.table.removeRow(row.row())
        else:
            QMessageBox.warning(self, "Warning", "No row selected to delete.")

    def get_params(self):
        params = []
        for row in range(self.table.rowCount()):
            param = {
                "name": self.table.item(row, 0).text() if self.table.item(row, 0) else "",
                "type": self.table.cellWidget(row, 1).currentText(),
                "value": self.table.item(row, 2).text() if self.table.item(row, 2) else "",
                "Description": self.table.item(row, 3).text() if self.table.item(row, 3) else "",
                "unit": self.table.item(row, 4).text() if self.table.item(row, 4) else ""
            }
            params.append(param)
        return params


class EMTTab(ParamEditor):
    pass